package flinkSql.test;


import bean.SensorReading;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.types.Row;
import org.junit.Test;

import static org.apache.flink.table.api.Expressions.$;

public class Flink_SQL_Bean_Table {
    @Test
    public void test() throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment().setParallelism(1);
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        SingleOutputStreamOperator<SensorReading> input = env.socketTextStream("node193", 9999)
                .map((MapFunction<String, SensorReading>) value -> {
                    String[] split = value.split(",");
                    return new SensorReading(split[0], Long.parseLong(split[1]), Double.parseDouble(split[2]));
                });

        //SQL风格 流注册，转换表
        tableEnv.createTemporaryView("sensor", input);
        // 查询
        Table table = tableEnv.sqlQuery("select * from sensor");
        //表转换流输出结果
        tableEnv.toRetractStream(table, Row.class).print();

        Table table1 = tableEnv.fromDataStream(input);
        Table tableResult = table1.groupBy($("id")).select($("id"),$("temp").count());
        tableEnv.toRetractStream(tableResult,Row.class).print("SQL");
        env.execute();
    }
}
